# -*- coding:utf-8 -*-
"""
与服务端通信并处理相关动作
"""
import socket
import json
import time
import win32api
import win32con
import GlobalVar
import MyFunc


class MessageClient:
    def __init__(self, server_ip='127.0.0.1', server_port=8080):
        self.socket = None
        self.connection(server_ip, server_port)

        pass

    def connection(self, server_ip, server_port):
        """
        连接服务器
        :param server_ip: 服务器ip
        :param server_port: 服务端口
        :return: 
        """
        self.socket = socket.socket()
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        self.socket.setblocking(True)
        self.socket.connect((server_ip, server_port))
        host = MyFunc.getIp(False)
        self.send_control(host)

    def monitor(self):
        """
        监控消息
        :return: 
        """
        while True:
            ret_b = self.socket.recv(1024)
            time.sleep(0.001)
            if ret_b:
                for ret_bytes in MyFunc.format_recv(ret_b):
                    ret_bytes = json.loads(ret_bytes)
                    if ret_bytes['action'] == 'keyboard':  # 键盘事件,接收控制按键id并处理
                        GlobalVar.set_lock('lock')
                        key_id = int(ret_bytes['data'][1:])
                        key_action = ret_bytes['data'][0]

                        if key_action == 'd':
                            win32api.keybd_event(key_id, 0, 0, 0)  # 按下按键
                        if key_action == 'u':
                            win32api.keybd_event(key_id, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键

                            GlobalVar.set_lock('unlock')

                    if ret_bytes['action'] == 'list':  # 列表消息,在窗口更新连接列表
                        GlobalVar.set_list(ret_bytes['data'])

    def send_keyboard(self, msg):
        """
        发送键盘事件
        :param msg: 
        :return: void
        """
        msg = {
            'action': 'keyboard',
            'data': msg
        }
        msg = json.dumps(msg)
        self.socket.send(msg)

    def send_control(self, ip):
        """
        发送控制切换
        :param ip: 
        :return: void
        """
        msg = {
            'action': 'control',
            'data': ip
        }
        self.socket.send(json.dumps(msg))
